package org.itboys.advertisement.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.itboys.advertisement.constant.AdvertisementConstant;
import org.itboys.advertisement.entity.AdvertisementItem;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.oss.OssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 广告元素管理
 */
@Service
public class AdvertisementItemService  extends BaseService<AdvertisementItem, Long> {

	private static final long serialVersionUID = 1L;
	
	/**
     * ossCdn 的二级域名前缀
     */
    private String urlPrefix = "http://digitalcity.oss-cn-hangzhou.aliyuncs.com/";
	
	@Resource(name="advertisementDs")
    private MongoDataSource advertisementDs;
	@Resource(name = "weigeOssService")
    OssService weigeOssService;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return advertisementDs;
    }

    @Override
    protected Class<AdvertisementItem> getEntityClass() {
        return AdvertisementItem.class;
    }

    public List<AdvertisementItem> getItems(long advertisementId) {
        return advertisementDs.find(AdvertisementItem.class).field("advertisementId").equal(advertisementId)
                .order("order").asList();
    }
    
    /**
     * 新增或者修改
     * @param advertisement
     * @return
     */
    public boolean insert(AdvertisementItem advertisementItem, MultipartFile file){
    	try{
    		String tempFile = null;
    		if(file != null && !file.isEmpty()){
    			tempFile = weigeOssService.upload(file.getInputStream(), AdvertisementConstant.AdvertisementItem.OSS_PATH);
    			advertisementItem.setFilePath(urlPrefix + AdvertisementConstant.AdvertisementItem.OSS_PATH + "/" + tempFile);
			}
    		
    		if(advertisementItem.getId() != 0){
    			if(StringUtils.isBlank(tempFile)){
    				AdvertisementItem ai = super.getById(advertisementItem.getId());
    				advertisementItem.setFilePath(ai.getFilePath());
    			}
    			super.update(advertisementItem);
    		}else{
    			super.save(advertisementItem);
    		}
    		return true;
    	}catch(Exception e){
    		logger.error("AdvertisementItemService.insert error, advertisementItem=" + ToStringBuilder.reflectionToString(advertisementItem), e);
    		return false;
    	}
    }
    
    /**
     * 删除
     * @param advertisementId
     * @return
     */
    public boolean dele(Long advertisementItemId){
    	try{
    		super.delete(advertisementItemId);
    		return true;
    	}catch(Exception e){
    		logger.error("AdvertisementService.dele error, advertisementItemId=" + advertisementItemId, e);
    		return false;
    	}
    }
    
}
